package com.gem.taskplan.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gem.taskplan.adapter.TaskDoneAdapter;
import com.gem.taskplan.javaBean.DoneBean;
import com.gem.taskplan.service.CheckedNetWork;
import com.gem.taskplan.util.HttpUtil;
import com.gem.taskplan.util.PropertiesUtil;

import android.R.string;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("ValidFragment")
public class Fragment3 extends Fragment {

	static String url = "/TaskServlet";
	private static Context context;
	private static ListView listView;
	private static String curProjectName;
	private  String curTeamName;  
	private  String curUser;
	private static TaskDoneAdapter  MyAdapter3;
	private static List<DoneBean> list = new ArrayList<DoneBean>();
	private SwipeRefreshLayout refreshDone;

	public Fragment3(Context context1,Bundle data,String curProjectName1,String teamName) {
		context = context1;
		this.curTeamName = teamName;
		curProjectName = curProjectName1;
		this.curUser = context.getSharedPreferences("taskPlanShare", Activity.MODE_PRIVATE).getString("lastUser", "");
		/************获得访问服务器的地址***************/
		url = "/TaskServlet";
		url = PropertiesUtil.getServerURL(context)+url;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
		listView = (ListView) v.findViewById(android.R.id.list);
		refreshDone = (SwipeRefreshLayout) v.findViewById(R.id.refreshTask);
		//添加刷新颜色变化
		refreshDone.setColorScheme(android.R.color.holo_red_light, android.R.color.holo_green_light,
				android.R.color.holo_blue_bright, android.R.color.holo_orange_light);
		
		MyAdapter3 = new TaskDoneAdapter(context, list, R.layout.content_list3);
		listView.setAdapter(MyAdapter3);
		initFragment3();
		
		return v;
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		//simpleAdapter = new SimpleAdapter(getActivity(), list, R.layout.content_list, new String[]{"content","start_time","end_time"}, new int[]{R.id.task_content,R.id.task_member,R.id.end_time} );
		MyAdapter3 = new TaskDoneAdapter(context, list, R.layout.content_list3);
		listView.setAdapter(MyAdapter3);
		initFragment3();

		/**********doing界面的ListView条目被点击的点击事件********/
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent,
					View view, int position, long id) {
				System.out.println("任务被点击了");
				/****点击跳转到详情界面******/
				Intent intent = new Intent(context,TaskInfoActivity.class);
				TextView textView = (TextView) view.findViewById(R.id.task_content3);
				TextView task_member1 = (TextView) view.findViewById(R.id.task_member3);
				TextView end_time1 = (TextView) view.findViewById(R.id.finish_time);
				intent.putExtra("taskName", textView.getText().toString());
				intent.putExtra("taskMembers", task_member1.getText().toString());
				intent.putExtra("taskOutTime", end_time1.getText().toString());
				intent.putExtra("ProjectName", curProjectName);
				intent.putExtra("TeamName", curTeamName);
				intent.putExtra("taskType", "完成");
				startActivityForResult(intent, 3);
			}
		});
		/**********done界面的ListView条目被长按的长按事件********/
		listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View view,
					int pos, long arg3) {

				final TextView text = (TextView) view.findViewById(R.id.task_content3);
				final int position = pos;
				//弹出窗口选择是否删除该任务
				new AlertDialog.Builder(context).setIcon(R.drawable.delete).setTitle("删除任务")
				.setMessage("您确定要删除 “ "+text.getText().toString()+" ” 吗？")
				.setPositiveButton("删除", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
						/*********判断是否联网***************/
						if(!CheckedNetWork.checkedConnection(context)){
							return;
						}
						
						Map<String, String> map = new HashMap<String, String>();
						map.put("taskName",text.getText().toString());
						map.put("curName", curUser);
						map.put("curProjectName", curProjectName);
						map.put("action", "deleteTask");
						String result = null;
						try {
							result = HttpUtil.postRequest(url, map);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(result.equals("notCreator")){
							Toast.makeText(context, "您不是该任务的创建者，不能删除该任务！", Toast.LENGTH_SHORT).show();
							return;
						}else if(result.equals("yes")){
							list.remove(position);
							MyAdapter3.notifyDataSetChanged();
							Toast.makeText(context, "已成功删除该任务！", Toast.LENGTH_SHORT).show();
						}else {
//							Toast.makeText(context,"网络异常，请稍后重试！", Toast.LENGTH_SHORT).show();
						}
					}
				}).setNegativeButton("取消",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				}).create().show();
				
				return false;
			}

		});

		/************下拉刷新监听**************/
		refreshDone.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				new Handler().postDelayed(new Runnable() {
					public void run() {
						refreshDone.setRefreshing(false);
						initFragment3();//重新访问服务器请求新数据
					}
				}, 500);
			}
		});
	}

	
	
	
	public static void setData3(Bundle aa ){
		if(aa!=null){
			String content = aa.getString("content");
			String member = aa.getString("member");
			String endtime = aa.getString("endtime");
			String attachment = aa.getString("attachment");
			DoneBean bean = new DoneBean();
			bean.setContent(content);
			bean.setMember(member);
			bean.setEndtime(endtime);
			bean.setTask_attachment(attachment);
			bean.setTask_progress("0/0");
			bean.setTask_message("0");
			list.add(0,bean);
			MyAdapter3.notifyDataSetChanged();
		}
	}

	//从服务器获取任务信息
	public static void initFragment3(){
		if(!CheckedNetWork.checkedConnection((Activity)context)){
			return;
		}
		String curUser = context.getSharedPreferences("taskPlanShare", Activity.MODE_PRIVATE).getString("lastUser", "");
		Map<String, String> map = new HashMap<String, String>();
		map.put("curUser",curUser);
		map.put("curProjectName", curProjectName);
		map.put("action", "queryDone");
		String result = null;
		try {
			result = HttpUtil.postRequest(url, map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Fragment3界面---------"+result);
		if (result==null) {
			return;
		}
		String[] key = new String[]{"task_name","membersName","subTaskFinishNumber","subTaskNumber","commentsNumber","attchmentNumber","task_outOfDate","task_zan"};
		try {
			JSONObject object = new JSONObject(result);
			JSONArray array = object.getJSONArray("taskListJson");
			list.clear();
			for(int i=0 ; i<array.length(); i++){
				JSONObject object1 = array.getJSONObject(i);
				JSONArray array1 = object1.getJSONArray("taskListJson"+i);
				DoneBean bean = new DoneBean();
				bean.setContent(array1.getJSONObject(0).getString(key[0]));
				bean.setMember(array1.getJSONObject(1).getString(key[1]));
				bean.setTask_message(array1.getJSONObject(4).getString(key[4]));
				bean.setTask_attachment( array1.getJSONObject(5).getString(key[5]));
				bean.setEndtime(array1.getJSONObject(6).getString(key[6]));
				bean.setZanNumber(Integer.parseInt(array1.getJSONObject(7).getString(key[7])));
				list.add(bean);   
			}
			MyAdapter3 = new TaskDoneAdapter(context, list, R.layout.content_list3);
			MyAdapter3.notifyDataSetChanged();//刷新
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}

